/* eslint-disable no-bitwise */
/* eslint-disable func-names */

export const confirmThePromptTwice = (
  handler: () => void,
  mes = '你确定要删除该条记录吗？',
  title = '温馨提示',
  cancel = () => {},
  confirmButtonText = '确定',
  cancelButtonText = '取消'
) => {
  ElMessageBox.confirm(mes, title, {
    confirmButtonText,
    cancelButtonText,
    closeOnClickModal: false,
    type: 'warning',
    draggable: true,
  })
    .then(() => {
      handler();
    })
    .catch(() => {
      cancel();
    });
};

/**
 * 获取uuid
 */
export function generateUuid(): string {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;

    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

/**
 * 基于种子的伪随机数生成器
 * @param {string} seed - 种子字符串
 */
function seededRandomGenerator(seed: string) {
  let h = 0;
  // 将种子字符串转换为数字种子
  for (let i = 0; i < seed.length; i++) {
    h = (Math.imul(31, h) + seed.charCodeAt(i)) | 0;
  }

  let seedNum = Math.abs(h);

  // 返回一个生成随机数的函数
  return function () {
    // LCG 参数
    seedNum = (seedNum * 48271) % 0x7fffffff;
    return (seedNum & 0x7fffffff) / 0x7fffffff;
  };
}

/**
 * 生成指定范围内的随机数
 */
export function getRandomNumber(min: number, max: number, seed: string, withDecimal = false) {
  // 使用种子生成随机数生成器，或使用 Math.random 作为默认
  const rng = seed ? seededRandomGenerator(seed) : Math.random;

  // 生成随机数
  const randomNum = rng() * (max - min) + min;

  return withDecimal ? parseFloat(randomNum.toFixed(2)) : Math.floor(randomNum);
}

/** 随机排序 */
export function randomSort(array: any[]) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]]; // 交换元素
  }
  return array;
}

/**
 * 将指定数字按比例分成 n 份，基于种子生成相同的分配结果
 */
export function splitNumberWithSeed(total: number, parts: number, seed: string) {
  const rng = seededRandomGenerator(seed);

  // 随机生成 `parts` 个比例，并计算总和
  const ratios = Array.from({ length: parts }, () => rng());
  const sumRatios = ratios.reduce((a, b) => a + b, 0);

  // 按比例分配 `total`，并确保总和保持精度
  const result = ratios.map((ratio) => (ratio / sumRatios) * total);

  // 四舍五入，确保总和等于 total
  const roundedResult = result.map((value) => parseFloat(value.toFixed(2)));
  let difference = total - roundedResult.reduce((a, b) => a + b, 0);

  // 调整误差
  for (let i = 0; Math.abs(difference) > 0.01 && i < roundedResult.length; i++) {
    roundedResult[i]! += Math.sign(difference) * 0.01;
    difference = total - roundedResult.reduce((a, b) => a + b, 0);
  }

  return roundedResult;
}

/** 图片下载  */
export function downloadPicture(imgSrc: string, name?: string) {
  const image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute('crossOrigin', 'anonymous');
  image.onload = () => {
    const canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;
    const context = canvas.getContext('2d');
    context!.drawImage(image, 0, 0, image.width, image.height);
    const url = canvas.toDataURL('image/jpg');
    const a = document.createElement('a');

    a.download = name || `img_${Date.now()}`;
    a.href = url;
    a.click();
    a.remove();
  };
  image.src = imgSrc;
}
/**
 * 下载
 */
export function easeDownloadFile(blob: Blob | string | undefined, name: string | undefined) {
  if (!blob) {
    ElToast.error('下载失败');
    return;
  }
  const fileName = name || `file_${Date.now()}`;
  if (typeof blob === 'string') {
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = blob;
    link.setAttribute('download', fileName);
    link.click();
    // link.remove();
  } else {
    const reader = new FileReader();
    reader.readAsText(blob);
    reader.onload = function (res: ProgressEvent<FileReader>) {
      try {
        const resData = JSON.parse(res?.target?.result as string);
        if (resData.returnCode) {
          ElToast.error(resData.returnMsg || '下载失败');
        }
      } catch (err) {
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        link.setAttribute('download', fileName);
        link.click();
        link.remove();
        URL.revokeObjectURL(link.href);
      }
    };
  }
}

/**
 * 在树级中回溯
 */
export function getFathersById(id: any, originData: any[], prop = 'id', res = 'id', children = 'children') {
  const arrRes: Array<any> = [];
  const rev = (data: any, nodeId: any) => {
    for (let i = 0, length = data.length; i < length; i++) {
      const node = data[i];
      if (node[prop] === nodeId) {
        arrRes.unshift(node[res]);
        return true;
      } else {
        if (node[children] && node[children].length) {
          if (rev(node[children], nodeId)) {
            arrRes.unshift(node[res]);
            return true;
          }
        }
      }
    }
    return false;
  };
  rev(originData, id);
  return arrRes;
}
